<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-upload2" size="mini" @click="handleAdd"
          v-hasPermi="['ranCloud:ranFiles:add']">上传文件</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-upload2" size="mini" @click="handleCreateFile"
          v-hasPermi="['ranCloud:ranFiles:add']">创建文件夹</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row v-if="treeC.length == 0">
      <el-col>
          <strong>全部文件</strong>
      </el-col>
    </el-row>
    <el-row v-else>
      <el-col>
          <span @click="backOne" style="color: #06a7ff;cursor: pointer;">返回上一级 | </span>
          
          <span @click="backAll" style="color: #06a7ff;cursor: pointer;">全部文件</span>
          <span v-for="(item, index) in treeC" :key="index"> 
            {{ " > " + item }}
          </span>
      </el-col>
    </el-row>
    <el-skeleton :loading="statusData" animated >
      <template slot="template">
        <div style="display: flex;justify-content: space-between;align-items: center;margin: 10px 0;">
          <el-skeleton-item variant="h3" style="width: 30%;height: 40px;" />
          <el-skeleton-item variant="h3" style="width: 10%;height: 40px;" />
          <el-skeleton-item variant="h3" style="width: 10%;height: 40px;" />
          <el-skeleton-item variant="h3" style="width: 20%;height: 40px;" />
          <el-skeleton-item variant="h3" style="width: 20%;height: 40px;" />
        </div>
        <div v-for="(i, index) in 10" :key="index" style="display: flex;justify-content: space-between;align-items: center;margin: 10px 0;">
          <el-skeleton-item style="height: 40px;width: 40px;border-radius: 5px;" />
          <el-skeleton-item variant="h3" style="width: 45%;height: 40px;" />
          <el-skeleton-item variant="h3" style="width: 30%;height: 40px;" />
          <el-skeleton-item variant="h3" style="width: 15%;height: 40px;" />
        </div>
      </template>
      <template>
        <el-table
          :data="fileTrees"
          style="width: 100%"
          :default-sort = "{prop: 'fileUpdate', order: 'descending'}"
          @cell-mouse-enter="handleCell"
          v-if="fileTrees.length > 0"
          >
          <el-table-column
            prop="fileName"
            sortable 
            label="文件名"
            >
            <template slot-scope="scope">
             <div v-if="scope.row.fileType == '文件夹'" class="docName" @click="treeFileC(scope.row.fileName)">
              <i class="el-icon-folder" style="color: #06a7ff;font-size: 32px;margin-right: 20px;"></i>
              <span >{{ scope.row.fileName }}</span>
             </div>
             <div v-else class="docName" @click="handlePreview(scope.row)">
              <i v-if="videoType.includes(scope.row.fileType)" class="el-icon-video-camera" style="color: #06a7ff;font-size: 30px;margin-right: 20px;"></i>
              <i v-else-if="imgType.includes(scope.row.fileType)" class="el-icon-picture-outline" style="color: #06a7ff;font-size: 30px;margin-right: 20px;"></i>
              <i v-else-if="zipType.includes(scope.row.fileType)" class="el-icon-collection" style="color: #06a7ff;font-size: 30px;margin-right: 20px;"></i>
              <i v-else-if="'sql' === scope.row.fileType" class="el-icon-coin" style="color: #06a7ff;font-size: 30px;margin-right: 20px;"></i>
              <i v-else class="el-icon-document" style="color: #06a7ff;font-size: 30px;margin-right: 20px;"></i>
              {{ handelText(scope.row.fileName) }}
             </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="fileType"
            label="文件类型"
            sortable 
            width="180">
          </el-table-column>
          <el-table-column
            sortable 
            prop="fileUpdate"
            label="修改日期"
            width="180">
          </el-table-column>
          <el-table-column
            prop="fileSize"
            sortable 
            label="大小">
            <template slot-scope="scope">
                <span>{{ scope.row.fileSize|| "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="操作">
            <template slot-scope="scope">
              <el-button 
                v-if="scope.row.fileType != '文件夹'"
                size="mini"
                icon="el-icon-view"
                type="text"
                @click="handlePreview(scope.row)">
                预览
              </el-button>
              <el-button 
                v-if="scope.row.fileType != '文件夹'"
                size="mini"
                icon="el-icon-download"
                type="text"
                @click="handleDownLoad(scope.row)">
                下载
              </el-button>
              <el-button 
                size="mini"
                icon="el-icon-delete"
                type="text"
                @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty style="margin-top: 20px;" v-else description="里面空空如也"></el-empty>
      </template>
    </el-skeleton>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 上传文件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item prop="fileUrl">
          <file-upload-plus @handleFileDataSingle="handleFileDataSingle" :path="nowPath" @changeFile="handleFileData" v-model="form.fileUrl" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

     <!-- 创建文件夹弹框 -->
     <el-dialog title="创建文件夹" :visible.sync="openCreate" width="500px" append-to-body>
      <el-form ref="formFile" :model="formFile" :rules="rulesFile" label-width="80px">
        <el-form-item label="名称" prop="fileName">
          <el-input v-model="formFile.fileName" placeholder="请输入文件夹名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormFile">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 预览弹框 -->
    <DialogPreview 
    ref="dialogPreview" 
    :full="false" 
    :dialogVisible="openPreview"
    @closeDialog="handleDialog"
    ></DialogPreview>
  </div>
</template>
  
<script>

import { listRanFiles, getRanFiles, delRanFiles, addRanFiles, updateRanFiles, ranFileDownload, ranCreateFile, ranDeleteFile,listFileTree } from "@/api/ranCloud/ranFiles";

export default {
  name: "RanFiles",
  dicts: ['ran_cloud_file'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 云盘文件表格数据
      ranFilesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 创建文件夹弹出层
      openCreate: false,
      openPreview: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        fileUrl: null,
        fileType: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 创建文件夹表单
      formFile: {},
      // 表单校验
      rules: {
        fileName: [
          { required: true, message: "文件名不能为空", trigger: "blur" }
        ],
        fileUrl: [
          { required: true, message: "文件路径不能为空", trigger: "blur" }
        ],
        fileType: [
          { required: true, message: "文件类型不能为空", trigger: "change" }
        ],
      },
      rulesFile: {
        fileName: [
          { required: true, message: "文件夹名称不能为空", trigger: "blur" }
        ],
      },
      fileList: [],
      fileTrees: [],
      treeP: "123",
      treeC: [],
      statusData: true,
      selectFileName: null,
      // 视频类型
      videoType: ['wmv', 'asf', 'asx', 'rm', 'rmvb', 'mp4', '3gp', 'mov', 'm4v', 'avi', 'dat', 'mkv', 'flv', 'vob'],
      // 图片类型
      imgType: ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'raw', 'WMF', 'webp', 'avif', 'apng'],
      // 压缩包类型
      zipType: ['rar', 'zip', '7z', 'cab', 'arj', 'lzh', 'tar', 'gz', 'ace', 'uue', 'bzjar', 'iso', 'mpq'],
    };
  },
  created() {
    this.treeP = this.$store.getters.userId
    this.getList();
  },
  computed: {
    nowPath() {
      return '/' + this.treeP + '/' + this.treeC.join("/")
    }
  },
  methods: {
    /** 查询云盘文件列表 */
    getList() {
      this.loading = true;
      this.statusData = true
      listFileTree({
        fileUrl: this.nowPath
      }).then(res => {
        this.fileTrees = res.data
        setTimeout(()=> {
          this.statusData = false
        }, 200)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openCreate = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        fileName: null,
        fileUrl: null,
        fileType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.formFile = {
        fileName: null
      }
      this.resetForm("form");
      this.resetForm("formFile");
    },
    // 进入文件夹
    treeFileC(treeFile){
      this.statusData = true
      this.treeC.push(treeFile)
      this.getList()
    },
    // 回根目录
    backAll(){
      this.treeC = []
      this.statusData = true
      listFileTree({
        fileUrl: "/" + this.treeP
      }).then(res => {
        this.fileTrees = res.data
        setTimeout(()=> {
          this.statusData = false
        }, 200)
      })
    },
    // 返回上一级
    backOne(){
      this.statusData = true
      this.treeC.splice(-1, 1)
      this.getList()
    },
    // 处理文件名显示
    handelText(text){
      let index = text.lastIndexOf('.')
      return text.substring(0,index)
    },
    handleCell(row, column, cell, event){
      console.log(row, column, cell, event)
    },
    /** 处理下载 */
    handleDownLoad(data) {
      let pathUrl = this.nowPath + "/" + data.fileName
      ranFileDownload(pathUrl).then(res => {
        console.log(res)
        this.$download.saveAs(res, data.fileName)
        this.$modal.msgSuccess("下载成功");
      })

    },
     /** 处理预览 */
     handlePreview(data) {
      let pathUrl = this.nowPath + "/" + data.fileName
      this.handleDialog(true)
      this.$refs.dialogPreview.filePreviewPDF(pathUrl, data.fileName)
    },
    /** 处理上传的图片数据 */
    handleFileData(data) {
      if (data == null || data == '') {
        this.form.fileName = null;
        this.form.fileType = null;
      } else {
        this.form.fileName = this.getFileName(data[0].name)
        this.handleFileType(this.form.fileName)
      }
    },
    // 创建文件夹弹框
    handleCreateFile(){
      this.openCreate = true
    },
    // 处理单文件上传事件
    handleFileDataSingle(){
      this.open = false;
      this.form.fileUrl = ''
      this.getList();
      this.$modal.msgSuccess("上传成功");
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return "";
      }
    },
    // 获取当前格式
    handleFileType(fileName) {
      var type = fileName.slice(fileName.lastIndexOf(".") + 1);
      this.form.fileType = type
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "上传文件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fileId = row.fileId || this.ids
      getRanFiles(fileId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "上传文件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fileId != null) {
            updateRanFiles(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRanFiles(this.form).then(response => {
              this.$modal.msgSuccess("上传成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 创建文件夹表单提交按钮
    submitFormFile(){
      this.$refs["formFile"].validate(valid => {
        if (valid) {
          ranCreateFile(this.nowPath + '/' + this.formFile.fileName).then(res => {
            if(res.code = 200){
              this.openCreate = false
              this.reset()
              this.getList()
              this.$modal.msgSuccess('创建成功')
            }else {
              this.$modal.error(res.msg)
            }
          })
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileName = row.fileName;
      let pathUrl = this.nowPath + "/" + row.fileName
      this.$modal.confirm('是否确认删除文件"' + fileName + '"的数据项？').then(function () {
        return ranDeleteFile(pathUrl);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ranCloud/ranFiles/export', {
        ...this.queryParams
      }, `ranFiles_${new Date().getTime()}.xlsx`)
    },
    // 处理预览弹框状态
    handleDialog(value){
      this.openPreview = value
    },
     // 获取文件后缀
     getFileType(name) {
        if (name) {
          if (name.lastIndexOf(".") > -1) {
            return name.slice(name.lastIndexOf(".")+1);
          } else {
            return false
          }
        }
      },
  }
};
</script>
<style scoped>
  .docName {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
  .docName:hover {
    color: #06a7ff;
  }
</style>